<template>
  <div name="userManagement" class="management">
    <el-form :inline="true" :model="searchForm">
    <!--搜索框-->
    <el-form-item>
      <el-input
          v-model="searchForm.params.key"
          placeholder="查询id或名字"
          clearable>
      </el-input>
    </el-form-item>

    <el-form-item>
      <el-button @click="getListInfo">搜索</el-button>
      <el-button type="primary" @click="dialogFormVisible = true" >新增</el-button>
      <!--确认按钮-->
      <el-popconfirm title="确定要删除这些记录吗？"
                     @confirm="delHandle(null)"
                     style="margin-left: 10px;">
        <el-button type="danger"
                   slot="reference"
                   :disabled="delBtnStu">批量删除</el-button>
      </el-popconfirm>

    </el-form-item>
    </el-form>

    <el-table
        ref="multipleTable"
        border
        stripe
        :data="ListInfo"
        tooltip-effect="dark"
        style="width: 100%"
        @selection-change="handleSelectionChange">
      <el-table-column
          type="selection"
          width="55">
      </el-table-column>

      <el-table-column
          prop="userId"
          label="用户id"
          width="100">
      </el-table-column>
      <el-table-column
          prop="username"
          label="用户名"
          width="100">
      </el-table-column>
      <el-table-column
          prop="telephone"
          label="电话"
          width="100">
      </el-table-column>

      <el-table-column
          prop="email"
          label="邮箱"
          width="100">
        <template slot-scope="scope">
          {{textChange(scope.row.email)}}
        </template>
      </el-table-column>

      <el-table-column
          prop="statusName"
          label="状态"
          width="100">
      </el-table-column>

      <el-table-column
          label="医生认证"
          width="110">
        <el-button
            slot-scope="scope"
            @click="showMoreInfo(scope.row)">
          {{statusChange(scope.row.isDoctor)}}
        </el-button>
      </el-table-column>

      <el-table-colum
          label="创建时间"
          width="100">
        <template slot-scope="scope">
          {{timeChange(scope.row.createTime)}}
        </template>
      </el-table-colum>

      <el-table-column
          width="150px"
          label="操作">
        <template slot-scope="scope">
          <el-button type="text"
                     @click="editHandle(scope.row.userId)"
          >编辑</el-button>

          <el-divider direction="vertical"></el-divider>

          <el-popconfirm title="确定要删除这条记录吗？"
                         @confirm="delHandle(scope.row.userId)">
            <el-button type="text" slot="reference">删除</el-button>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <!--页码-->
    <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="current"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="size"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
    </el-pagination>


    <!--其他信息弹出框-->
    <el-dialog :visible.sync="showMoreInfoDig"
               title="医生信息">

      <el-descriptions
          :column="2"
          border
          direction="vertical">
        <el-descriptions-item >
          <template slot="label">
            <i class="el-icon-document"></i>
            医生id
          </template>
          {{moreInfo.doctor.drId}}
        </el-descriptions-item>

        <el-descriptions-item >
          <template slot="label">
            <i class="el-icon-document"></i>
            医生姓名
          </template>
          {{moreInfo.doctor.realName}}
        </el-descriptions-item>

        <el-descriptions-item>
          <template slot="label">
            <i class="el-icon-document"></i>
            职称
          </template>
          {{moreInfo.doctor.titleName}}
        </el-descriptions-item>

        <el-descriptions-item >
          <template slot="label">
            <i class="el-icon-document"></i>
            科室
          </template>
          {{moreInfo.doctor.departmentName}}
        </el-descriptions-item>
        <el-descriptions-item >
          <template slot="label">
            <i class="el-icon-document"></i>
            所属医院
          </template>
          {{moreInfo.doctor.hospitalName}}
        </el-descriptions-item>


      </el-descriptions>
    </el-dialog>


    <!--&lt;!&ndash;用户信息弹出框&ndash;&gt;-->
    <!--<el-dialog :visible.sync="showUserMoreInfoDig"-->
    <!--           title="用户信息">-->

    <!--  <el-descriptions-->
    <!--      :column="2"-->
    <!--      border-->
    <!--      direction="vertical">-->
    <!--    <el-descriptions-item >-->
    <!--      <template slot="label">-->
    <!--        <i class="el-icon-document"></i>-->
    <!--        用户id-->
    <!--      </template>-->
    <!--      {{moreInfo.user.userId}}-->
    <!--    </el-descriptions-item>-->

    <!--    <el-descriptions-item >-->
    <!--      <template slot="label">-->
    <!--        <i class="el-icon-document"></i>-->
    <!--        用户名-->
    <!--      </template>-->
    <!--      {{moreInfo.user.username}}-->
    <!--    </el-descriptions-item>-->

    <!--    <el-descriptions-item>-->
    <!--      <template slot="label">-->
    <!--        <i class="el-icon-document"></i>-->
    <!--        邮箱-->
    <!--      </template>-->
    <!--      {{textChange(moreInfo.user.email)}}-->
    <!--    </el-descriptions-item>-->

    <!--    <el-descriptions-item >-->
    <!--      <template slot="label">-->
    <!--        <i class="el-icon-document"></i>-->
    <!--        电话-->
    <!--      </template>-->
    <!--      {{textChange(moreInfo.user.telephone)}}-->
    <!--    </el-descriptions-item>-->
    <!--    <el-descriptions-item >-->
    <!--      <template slot="label">-->
    <!--        <i class="el-icon-document"></i>-->
    <!--        状态-->
    <!--      </template>-->
    <!--      {{moreInfo.user.statusName}}-->
    <!--    </el-descriptions-item>-->

    <!--  </el-descriptions>-->
    <!--</el-dialog>-->

    <!--编辑弹窗-->
    <el-dialog title="信息"
               :visible.sync="dialogFormVisible"
               width="600px"
               @closed="resetForm('editForm')">
      <el-form :model="editForm"
               :rules="editFormRules"
               ref="editForm">
        <el-form-item label="用户名" prop="username" label-width="100px">
          <el-input v-model="editForm.username"
                    autocomplete="off"></el-input>
        </el-form-item>

        <el-form-item label="密码" prop="password" label-width="100px">
          <el-input v-model="editForm.password"
                    autocomplete="off" show-password></el-input>
        </el-form-item>

        <el-form-item label="用户状态" prop="userStatus" label-width="100px">
          <el-select v-model="editForm.userStatus"
                     autocomplete="off">
            <el-option v-for="item in statusList"
                       :key="item.id"
                       :value="item.id"
                       :label="item.status">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="电话" prop="telephone" label-width="100px">
          <el-input v-model="editForm.telephone"
                     autocomplete="off">
          </el-input>
        </el-form-item>

        <el-form-item label="邮箱" prop="email" label-width="100px">
          <el-input v-model="editForm.email"
                     autocomplete="off">
          </el-input>
        </el-form-item>

        <el-form-item label="认证状态" prop="isDoctor" label-width="100px">
          <el-select v-model="editForm.isDoctor"
                     autocomplete="off">
            <el-option
                :value="true"
                label="已认证">
            </el-option>
            <el-option
               :value="false"
               label="无认证">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="ip锁定" prop="ipLock" label-width="100px">
          <el-input v-model="editForm.ipLock"
                    autocomplete="off" placeholder="0.0.0.0 无锁定"></el-input>
        </el-form-item>


      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="resetForm('editForm')">取 消</el-button>
        <el-button type="primary" @click.native="submitEditForm('editForm')">确 定</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
export default {
  name: "userManagement",
  data(){

    let validateId = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('绑定的用户账号'));
      }
      let regex = /^\d{5,}$/;
      if(!regex.test(value)){
        callback(new Error('非合法账号格式'));
      }
      callback();
    };

    let validatePhone = (rule, value, callback) => {
      let pattern = /^(13[0-9]|14[5|7]|15[0-9]|1[6|8-9][0-9])\d{8}$/;
      if (value === '') {
        console.log(value);
        callback(new Error('电话不能为空'));
      }
      if (!pattern.test(value)) {
        console.log(value);
        console.log(pattern.test(value));
        callback(new Error('请输入正确手机号码'));
      }
      callback();
    };

    let validateEmail=(rule, value, callback)=>{
      let pattern = /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*|$/;
      if(value === '')
        return;
      if(!pattern.test(value))
        callback(new Error('非法邮箱信息'));

      callback()
    };

    let validateUsername = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入用户名'))
      }
      let regex = /^[0-9]*$/;
      if(regex.test(value)){
        callback(new Error('非纯数字'));
      }
      if(value.length < 2 || value.length > 16)
        callback(new Error('用户名长度[2-16]'))

      callback();
    };

    let validateIP = (rule, value, callback)=>{
      let pattern = /((2(5[0-5]|[0-4]\d))|[0-1]?\d{1,2})(\.((2(5[0-5]|[0-4]\d))|[0-1]?\d{1,2})){3}/;
      if(value !== '' && !pattern.test(value)){
        callback(new Error('非法ip地址'))
      }
      callback();
    };

    let validateChoice =(rule, value, callback)=>{
      if(value === '' || value === 0){
        callback(new Error('请选择选项'))
      }
      callback();
    }

    let validatePassword =(rule, value, callback)=>{
      let num = /^[0-9]*$/;//纯数字
      let charter = /^[A-Za-z]+$/; //纯字母
      if(num.test(value)){
        callback(new Error('密码由数字和字母组成'));
      }
      if(charter.test(value)){
        callback(new Error('密码由数字和字母组成'));
      }

      if(value.length < 8 || value.length >16)
        callback(new Error('密码长度为[8,16]'));

      callback();
    }

    return{
      //更多消息窗
      showMoreInfoDig: false,
      //更多消息
      showUserMoreInfoDig: false,

      //删除键
      delBtnStu: true,
      //编辑窗
      dialogFormVisible: false,

      //搜索对象
      searchForm: {
        data: '',
        method: "all-page",
        params: {
          current: this.current,
          key: '',
          id: 0,
          name: '',
          size: this.size
        }
      },
      //数据
      ListInfo: [
        {
          userId: 0,
          username: '',
          password: '',
          telephone: '',
          isDoctor: false,
          email: 0,
          userStatus: 0,
          gender: '',
          ipLock: '',

          createTime: '',
          updateTime: '',
          statusName: '',
        }
      ],

      //医生显示
      moreInfo:{ //patientId
        doctor:{
          drId: 0,
          hospitalId: 0,
          departmentId: 0,
          realName: '',
          title: 0,
          doctorStatus: 0,
          perInfo: '',
          userId: 0,

          hospitalName: '',
          titleName: '',
          statusName: '',
          departmentName: ''
        }
      },

      //状态
      statusList: [
      {
        id: 0,
        status: ''
      }
    ],


      //编辑窗口数据
      editForm: {
        userId: 0,
        username: '',
        password: '',
        telephone: '',
        isDoctor: false,
        email: 0,
        userStatus: 0,
        gender: 0,
        ipLock: '',

      },

      editFormRules: {
        username: [
          {required: true,validator: validateUsername, trigger:'blur'}
        ],

        telephone: [
          {required: true,validator: validatePhone, trigger:'blur'}
        ],

        // email: [
        //   {required: false,validator: validateEmail, trigger:'blur'}
        // ],

        ipLock: [
          {required: true,validator: validateIP, trigger:'blur'}
        ],

        password: [
          {required: true,validator: validatePassword, trigger:'blur'}
        ],

        isDoctor: [
          {required: true,validator: validateChoice, trigger:'blur'}
        ],
        userStatus: [
          {required: true,validator: validateChoice, trigger: 'blur'}
        ]
      },

      current: 1,
      total: 0,
      size: 10,

    }
  },
  created() {
    this.getListInfo();
    this.getOtherInfo();
  }
  ,methods: {
    getListInfo(){
      const self = this;
      let key = this.searchForm.params.key;
      let way = 'all-page';
      let idVal = 0;
      let nameVal = '';

      let regexName = /^[\u4E00-\u9FA5]+$/;
      let regexNum = /^\d{5,}$/;

      if(regexName.test(key)){
        way = 'name-page';
        nameVal = key.toString();
      }
      else if(regexNum.test(key)){
        way = 'id-page';
        idVal = Number(key);
      }

      let json = {
        method: way ,
        params: {
          'id': idVal,
          'name': nameVal,
          'current': self.current,
          'size': self.size
        }
      }

      self.$axios.post('api/user/findUserInfo',json)
          .then(res=>{
            self.ListInfo = res.data.data.data;
            self.current = res.data.data.currentPage;
            self.size = res.data.data.size;
            self.total = res.data.data.total;
          }).catch(err => {
        console.log(err)
      })

    },

    getOtherInfo(){
      const self = this;
      let json = {
        method: "all",
        params: {
          id: 0,
          name: ''
        }
      }

      this.$axios.get('api/user/getUserStatus')
          .then(res => {
            self.statusList = res.data.data;
          })
          .catch(err => {
            console.log(err);
          })
    },

    delHandle(id) {
      let ids = []
      id ? ids.push(id) : this.multipleSelection.forEach(row => {
        ids.push(row.userId)
      })
      console.log(ids)
      let url = 'api/user/deleteUserInfo'

      this.$axios.post(url, {'ids': ids}).then(res => {

        this.$message({
          showClose: true,
          message: '恭喜你，操作成功',
          type: 'success',
          onClose: () => {
            this.getListInfo()
          }
        });
      })
    },
    toggleSelection(rows) {
      if (rows) {
        rows.forEach(row => {
          this.$refs.multipleTable.toggleRowSelection(row);
        });
      } else {
        this.$refs.multipleTable.clearSelection();
      }
    },
    handleSelectionChange(rows) {
      this.multipleSelection = rows;
      this.delBtnStu = rows.length === 0
    },
    editHandle(id){
      console.log(id)
      let json = {
        'userId': id
      }
      this.$axios.post("api/user/selectUserInfoById",json).then(res => {
        this.editForm = res.data.data
        this.dialogFormVisible = true
      })

    },
    //换显示数
    handleSizeChange(val) {
      this.size = val
      this.getListInfo()
    },
    //换页
    handleCurrentChange(val) {
      this.current = val
      this.getListInfo()
    },
    //重置弹出表单
    resetForm(formName) {
      this.$refs[formName].resetFields();
      this.editForm = {}
      this.dialogFormVisible = false
      this.permDialogFormVisible = false
    },
    //提交编辑
    submitEditForm(formName){
      console.log(this.editForm.userId);

      let choice = (Number(this.editForm.userId) !== 0
          && this.editForm.userId !== undefined
          && String(this.editForm.userId) !== '');

      this.$refs[formName].validate((valid) => {
        console.log("edit")
        if (valid) {
          this.$axios.post('api/user/' + ( choice
              ? "modifyUserInfo"
              : "addUserInfo") ,this.editForm)
              .then(res => {
                console.log(res.data)
                this.resetForm(formName)
                this.$message({
                  showClose: true,
                  message: '恭喜你，操作成功',
                  type: 'success',
                  onClose: () => {
                    this.getListInfo()
                  }
                });
              })
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },

    showMoreInfo(val){
      const self = this;
      let id = val.userId;
      let data = {
        'userId': id};
      if(Boolean(val.isDoctor) === false)
        return;

      this.$axios.post('api/doctor/selectDoctorByUserId', data)
          .then(res => {
            self.moreInfo.doctor = res.data.data;
            self.showMoreInfoDig = true;

          }).catch(err => {
        console.error("[error]")
        console.log(err);
      })


    },
    // showUserInfo(val){
    //   const self = this;
    //
    //   let userId = val.userId;
    //   let dataUser = {
    //     'userId': userId
    //   }
    //   this.$axios.post('api/user/selectUserInfoById',dataUser)
    //       .then(res => {
    //         self.moreInfo.user = res.data.data
    //         self.showUserMoreInfoDig = true;
    //       })
    // },

    timeChange(val){
      let str = val.toString();
      str = str.substring(0,19).replace('T',' ');

      return str;

    },
    textChange(val){
      if(val === null){
        return '暂无信息';
      }
      return val;
    },
    statusChange(val){
      let choice = Boolean(val);
      return choice ? '已认证':'无认证'
    }

  }
}
</script>

<style scoped>
  .management{
    margin: 15px 15px;
  }
  .el-pagination{
    margin: 0 auto; text-align: center;
    /*margin-top: 22px;*/
  }
</style>